package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.util.ShardingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class VmsJob {
    @Autowired
    private VendingMachineService vendingMachineService;

    @XxlJob("scheduledScanVmsHandler")
    public ReturnT<String> scheduledScanVmsHandler(String param) {
        // 获取分片参数
        ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
        int numbers = shardingVO.getTotal();  //分片总数
        int index = shardingVO.getIndex(); //当前分片索引

        // 查询售货机列表
        LambdaQueryWrapper<VendingMachineEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
                .apply("mod(id," + numbers + " ) = " + index);  //对id取模;
        List<VendingMachineEntity> vendingMachineEntities = vendingMachineService.list(queryWrapper);

        // 发送消息
        for (VendingMachineEntity vendingMachineEntity : vendingMachineEntities) {
            String innerCode = vendingMachineEntity.getInnerCode();
            vendingMachineService.createSupplyContractByInnerCode(innerCode);
        }

        return ReturnT.SUCCESS;
    }
}
